import { Notification, NotificationListResponse } from '../types/todo'

// API 基础配置
const API_BASE_URL = 'http://localhost:8000'

// 创建一个基础的 fetch 包装函数
async function apiRequest<T>(
  endpoint: string,
  options: RequestInit = {}
): Promise<T> {
  const url = `${API_BASE_URL}${endpoint}`
  
  const headers: Record<string, string> = {
    'Content-Type': 'application/json',
    ...options.headers as Record<string, string>,
  }
  
  // 添加认证 token
  const token = localStorage.getItem('auth_token')
  if (token) {
    headers.Authorization = `Bearer ${token}`
  }
  
  const config: RequestInit = {
    headers,
    ...options,
  }

  try {
    const response = await fetch(url, config)
    
    if (!response.ok) {
      if (response.status === 401) {
        localStorage.removeItem('auth_token')
        localStorage.removeItem('user_info')
        window.location.reload()
      }
      if (response.status === 403) {
        throw new Error('没有权限访问此资源')
      }
      throw new Error(`HTTP error! status: ${response.status}`)
    }
    
    const data = await response.json()
    return data
  } catch (error) {
    console.error(`API request failed: ${url}`, error)
    throw error
  }
}

// 通知 API 服务类
export class NotificationApiService {
  /**
   * 获取用户通知
   */
  static async getUserNotifications(limit?: number, unreadOnly?: boolean): Promise<NotificationListResponse> {
    const params = new URLSearchParams()
    if (limit) params.append('limit', limit.toString())
    if (unreadOnly) params.append('unread_only', 'true')
    
    const query = params.toString() ? `?${params.toString()}` : ''
    return apiRequest<NotificationListResponse>(`/notifications${query}`)
  }

  /**
   * 标记通知为已读
   */
  static async markNotificationAsRead(notificationId: number): Promise<{success: boolean, message: string}> {
    return apiRequest<{success: boolean, message: string}>(`/notifications/${notificationId}/read`, {
      method: 'PUT',
    })
  }
}

// 导出便捷的 API 方法
export const notificationApi = {
  // 通知管理
  getNotifications: (limit?: number, unreadOnly?: boolean) => 
    NotificationApiService.getUserNotifications(limit, unreadOnly),
  markAsRead: (notificationId: number) => 
    NotificationApiService.markNotificationAsRead(notificationId),
}

// 导出默认实例
export default notificationApi